<?php

namespace app\admin\service;

use app\model\Partners;
// use think\facade\Session;
use app\model\Videos;
use app\model\Cooperater;
use app\model\MonetaryStatistics;
use app\model\DailyCooperaterStatistics;
use think\facade\Db;
use think\facade\Request;
use think\facade\Cache;
use app\common\Error;
use app\common\Common;

class PartnersService
{
    private $partnersModel;
    private $cooperaterModel;
    private $videosModel;
    private $monetaryStatisticsModel;
    private $dailyCooperaterStatisticsModel;

    public function __construct(Partners $partnersModel, Cooperater $cooperaterModel,Videos $videosModel, MonetaryStatistics $monetaryStatisticsModel, DailyCooperaterStatistics $dailyCooperaterStatisticsModel)
    {
        $this->partnersModel = $partnersModel;
        $this->videosModel = $videosModel;
        $this->cooperaterModel = $cooperaterModel;
        $this->monetaryStatisticsModel = $monetaryStatisticsModel;
        $this->dailyCooperaterStatisticsModel = $dailyCooperaterStatisticsModel;
    }

    // 获取下拉列表
    public function getSelectList()
    {
        $data = $this->partnersModel->getDataByWhere(['status' => 1]);
        return $data;
    }

    // 添加/编辑版权方
    public function editPartners($params, $userInfo)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }

        $params['start_time'] = strtotime($params['start_time'] . ' 00:00:00');
        $params['end_time'] = strtotime($params['end_time'] . ' 23:59:59');
        // $params['admin_user_id'] = Session::get('user_id');
        $params['admin_user_id'] = $userInfo['user_id'];

        $id = $this->partnersModel->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }

    // 删除版权方
    public function deletePartners($id, $userInfo)
    {
        $saveData = [
            'id' => $id,
            'status' => 2,
            // 'admin_user_id' => Session::get('user_id'),
            'admin_user_id' => $userInfo['user_id'],
            'updated_at' => time()
        ];

        $id = $this->partnersModel->edit($saveData);

        if (!$id) {
            return false;
        }

        return true;
    }

    // 获取版权方详情
    public function getPartnersDetail($id)
    {
        $data = $this->partnersModel->getInfoById($id, 'id, name, abbreviation, start_time, end_time, type, payment_method, payee, collection_account, bank_name');
        $data['start_time'] = date('Y-m-d', $data['start_time']);
        $data['end_time'] = date('Y-m-d', $data['end_time']);

        return $data;
    }

    // 获取版权方列表
    public function getPartnersList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where[] = ['status', '=', 1];
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }

        $data = $this->partnersModel->getPagingDataByWhere($where, $page, $limit, 'id, name, type, abbreviation, start_time, end_time, payment_method, payee, collection_account, bank_name');
        return $data;
    }

    // 查看版权方作品
    public function getPartnersWorks($params)
    {
        $id = $params['id'];
        $where = ['is_delete' => 0, 'is_shelves' => 1, 'partners_id' => $id];

        $data = $this->partnersModel->getInfoById($id, 'id, name, type, start_time, end_time');

        if ($data['type'] == 2) {
            return [];
        }

        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $result = $this->videosModel->getPagingDataByWhere($where, $page, $limit, 'id, name, cooperation_mode, created_at, scale');

        foreach ($result['data'] as $key => $item) {

            $result['data'][$key]['scale'] = $item['cooperation_mode'] === 1 ? (100 - $item['scale']).'%' : '-';
            $result['data'][$key]['end_time'] = $data['end_time'];
        }

        return $result;
    }

    // 获取输入版权结算列表数据
    public function getEnterSettlementPartnersList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }

        if (!empty($params['start_date'])) {
            $startDate = intval(date('Ymd', strtotime($params['start_date'])));
            $where[] = ['date', '>', $startDate];
        }

        if (!empty($params['end_date'])) {
            $endDate = intval(date('Ymd', strtotime($params['end_date']) + 24 * 3600));
            $where[] = ['date', '<', $endDate];
        }

        $data = $this->monetaryStatisticsModel->getPagingDataByWhere($where, $page, $limit, 'id, name, partners_id, date, monetary, divided_amount');

        if (!empty($data['data'])) {
            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['date'] = substr($item['date'], 0, 4) . '-' . substr($item['date'], 4, 2) . '-' . substr($item['date'], 6, 2);
            }
        }

        return $data;
    }

    // 版权方下拉列表
    public function getCoOperativeSelectList()
    {
        $data = $this->partnersModel->getDataByWhere([], 'id, name');
        return $data;
    }

    //版权方下拉列表   //202310
    public function getCooperaterSelectList()
    {
        $where['status']=1;
        $where['is_delete']=1;
        $data = Db::name('admin')->where($where)->order('id', 'desc')->field('id,name')->select()->toArray();
        return $data;
    }

    // 短剧下拉列表  //202310
    public function getVideoNameSelectList()
    {
        $where['is_delete']=0;
        $where['is_copy']=0;
        $data = Db::name('videos')->where($where)->order('id', 'desc')->field('id,name')->select()->toArray();
        return $data;
    }

    // 添加/编辑合作方
    public function editCooperater($params)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }
        $dataErro=['code' => Error::FAIL_CODE, 'message' => Error::DO_NOT_ADD_AGAIN];


        // var_dump($params);exit;
        
        // if (empty($params['id']) && strpos($params['video_id'], ',') !== false) {
        if (empty($params['id'])) {
            $videoIds = explode(',', $params['video_id']);
            //添加的时候查看是否存在表里面,
            if(empty($params['video_id'])){
                return ['code' => Error::FAIL_CODE, 'message' => '剧不能为空'];
            }
            if(empty($params['admin_id'])){
                return ['code' => Error::FAIL_CODE, 'message' => '合作方不能为空'];
            }
            $where[]=['video_id','in',$videoIds];
            $where[]=['status','=',1];
            $where[]=['admin_id','=',$params['admin_id']];

            
            $videoIdData = Db::name('cooperater')->where($where)->field('id, video_id,video_name,admin_id')->select()->toArray();
            if(!empty($videoIdData)){
                return $dataErro;
            }

            foreach($videoIds as $k=>$v){
                $params['video_id']=$videoIds[$k];
                $videoData = $this->videosModel->getInfoById($videoIds[$k]);
                $params['video_name']=$videoData['name'];
                $id = $this->cooperaterModel->edit($params);
            }
        }else{
            //修改的时候查看是否存在表里面,
            if(empty($params['status'])){
                if(empty($params['video_id'])){
                    return ['code' => Error::FAIL_CODE, 'message' => '剧不能为空'];
                }
                if(empty($params['admin_id'])){
                    return ['code' => Error::FAIL_CODE, 'message' => '合作方不能为空'];
                }
            }
            if(!empty($params['video_id'])){
                $where[]=['video_id','=',$params['video_id']];
                $where[]=['status','=',1];
                $where[]=['admin_id','=',$params['admin_id']];

                $videoIdData = Db::name('cooperater')->where($where)->field('id, video_id,video_name,admin_id')->select()->toArray();
                if(!empty($videoIdData)){
                    return $dataErro;
                }
            }
            $id = $this->cooperaterModel->edit($params);
        }
        if (!$id) {
            return false;
        }
        return true;
    }

    // 获取合作方详情
    public function getCooperateretail($id)
    {
        $data = $this->cooperaterModel->getInfoById($id, 'id,admin_name,video_name,video_id,admin_id');

        return $data;
    }

    //合作方短剧列表展示   //202310
    public function getCooperaterList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where['status']=1;
        if (!empty($params['admin_name'])) {
            $where['admin_name'] = $params['admin_name'];
        }
        // $data = Db::name('cooperater')->where($where)->order('id', 'desc')->field('id,admin_name,video_name')->select()->toArray();
        $data = $this->cooperaterModel->getPagingDataByWhere($where, $page, $limit, 'id,admin_name,video_name');
        return $data;
    }

    //合作方统计列表展示   //202310
    public function getCooperaterCountList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 15;

        $where = [];
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }

        if (!empty($params['start_date'])) {
            $startDate = intval(date('Ymd', strtotime($params['start_date'])));
            $where[] = ['date', '>', $startDate];
        }

        if (!empty($params['end_date'])) {
            $endDate = intval(date('Ymd', strtotime($params['end_date']) + 24 * 3600));
            $where[] = ['date', '<', $endDate];
        }

        //加入权限，如果是管理员就展示所有，其他的人展示对应合作的剧
        $userInfo=$this->getLoginUserInfo();
        if (!empty($params['video_id'])) {
            $whereVideoIdData['video_id']=$params['video_id'];
        }
        if($userInfo['rule_id']!==1){
            $whereVideoIdData['status']=1;
            $whereVideoIdData['admin_id']=$userInfo['user_id'];
            $videoIdData = Db::name('cooperater')->where($whereVideoIdData)->field('id, video_id,video_name,admin_id')->select()->toArray();
        }else{
            $whereVideoIdData['status']=1;
            $videoIdData = Db::name('cooperater')->where($whereVideoIdData)->field('id, video_id,video_name,admin_id')->select()->toArray();
        }
        if(empty($videoIdData)){
            $data=[];
            return $data;
        }
        //历史数据只算合作方里面的
        if(!empty($videoIdData)){
            $videoIds = array_column($videoIdData, 'video_id');
            $where[]=['video_id','in',$videoIds];
        }
        $historyData1 = $this->dailyCooperaterStatisticsModel->getPagingDataByWhere($where, $page, $limit, 'video_name, video_id,total_price, date, self_price','date desc,video_id desc');
        //统计合计
        $historyData1Count = Db::name('daily_cooperater_statistics')->where($where)->field('sum(total_price) as total_amount, sum(self_price) as self_amount')->order('date desc,video_id desc')->select()->toArray();
        // var_dump($historyData1);exit;
        $historyData1['total_amount']=!empty($historyData1Count[0]['total_amount']) ? $historyData1Count[0]['total_amount'] : '0.00';
        $historyData1['self_amount']=!empty($historyData1Count[0]['self_amount']) ? $historyData1Count[0]['self_amount'] : '0.00';
        // var_dump($historyData1Count);exit;
        
        //如果筛选时间小于当前的时间则不展示
        if (!empty($params['end_date'])) {
            $endDate = intval(date('Ymd', strtotime($params['end_date'])));
            $nowDate=intval(date('Ymd', time()));
            if($endDate<$nowDate){
                //则不展示今天的，其他情况都要展示
                return $historyData1;
            }
        }
        //汇总今天的
        // 获取当天的数据
        foreach($videoIdData as $k=>$v){
            $todayData[]=$this->todayData($videoIdData[$k]['video_id']);
        }

        // 每页显示的记录数
        $pageSize = $limit;

        // 计算偏移量
        $offset = ($page - 1) * $pageSize;
        $limit=$offset - count($todayData);
        $historyData2 = Db::name('daily_cooperater_statistics')->where($where)->field('video_name, video_id,total_price, date, self_price')->order('date desc,video_id desc')->select()->toArray();
        // var_dump($historyData2);exit;
        // 合并当天数据和历史数据
        $data = array_merge($todayData, $historyData2);
        //合计
        $totalPriceArray=array_column($data, 'total_price');
        $selfPriceArray=array_column($data, 'self_price');
        $totalPrice=array_sum($totalPriceArray);
        $selfPrice=array_sum($selfPriceArray);
        // var_dump($data);exit;

        // 对数据进行分页处理
        $count = count($data); // 总记录数
        $totalPage = ceil($count / $pageSize); // 总页数

        // 根据当前页码和每页显示的记录数截取数据
        $currentPageData = array_slice($data, ($page - 1) * $pageSize, $pageSize);

        // 返回结果给前端
        $result = [
            'data' => $currentPageData,
            'total' => $count,
            'total_page' => $totalPage,
            'total_amount' => number_format($totalPrice,2),
            'self_amount' => number_format($selfPrice,2),
        ];
        

        return $result;
    }

    //统计某一部剧的当天数据
    public function todayData($videoId){
        //统计今日总充值和今日自投充值
        // $videoIdData = Db::name('cooperater')->where(['status' => 1])->field('id, video_id,video_name')->select()->toArray();

        // $videoIds = array_column($videoIdData, 'video_id');
        $date = date('Y-m-d', time());
        $startTime = strtotime($date);
        $endTime = strtotime($date . ' 23:59:59');
        //查看是否有复制剧
        $whereId['original_id']=$videoId;
        $videsData=Db::name('videos')->where($whereId)->field('id as video_id, name as video_name,is_copy,original_id')->select()->toArray();
        if(!empty($videsData[0]['original_id']) && $videsData[0]['original_id']>0){//如果存在复制剧
                $videoIds[]=$videoId;
                $videoIds[]=$videoId;
                $where = [
                    ['status', '=', 1],
                    ['pay_time', '>=', $startTime],
                    ['pay_time', '<=', $endTime],
                    ['video_id', 'in', $videoIds]
                ];
        }else{
            $where = [
                    ['status', '=', 1],
                    ['pay_time', '>=', $startTime],
                    ['pay_time', '<=', $endTime],
                    ['video_id', '=', $videoId]
                ];
        }
        $payData = Db::name('pay_record')->where($where)->field('video_id, sum(total_fee) as total_amount')->select()->toArray();
        $rechargeDataAmount = !empty($payData[0]['total_amount']) ? $payData[0]['total_amount'] : 0;
        // var_dump($payData);exit;
        

        //自投充值
        $where_per=[
            ['company_id', 'in', config('enum.self_company_id')]
        ];
        $distributor = Db::name('responsibility_person')->where($where_per)->field('id, name, commission_scale, scale, company_id')->select()->toArray();
        $pitcherIds = array_column($distributor, 'id');

        $linkData = Db::name('link')->where(['responsibility_person_id' => $pitcherIds])->field('id, responsibility_person_id')->select()->toArray();

        $linkIds = array_column($linkData, 'id');
        if(!empty($videsData[0]['original_id']) && $videsData[0]['original_id']>0){//如果存在复制剧
            $whereSelf=[
                ['status', '=', 1],
                ['pay_time', '>=', $startTime],
                ['pay_time', '<=', $endTime],
                ['link_id', 'in', $linkIds],
                ['video_id', 'in', $videoIds]
            ];
        }else{
            $whereSelf=[
                ['status', '=', 1],
                ['pay_time', '>=', $startTime],
                ['pay_time', '<=', $endTime],
                ['link_id', 'in', $linkIds],
                ['video_id', '=', $videoId]
            ];
        }

        $selfPayData = Db::name('pay_record')->where($whereSelf)->field('video_id, sum(total_fee) as total_amount')->select()->toArray();
        $selfPayDataAmount = !empty($selfPayData[0]['total_amount']) ? $selfPayData[0]['total_amount'] : 0;

        $videoData = $this->videosModel->getInfoById($videoId);
        // 今日数据
        $nowData['date']=date('Ymd', time());
        $nowData['month']=date('Ym', time());
        $nowData['video_name']=$videoData['name'];
        $nowData['video_id']=$videoId;
        $nowData['total_price']=number_format($rechargeDataAmount,2);
        $nowData['self_price']=number_format($selfPayDataAmount,2);
        return $nowData;
    }

    //获取用户信息
    public function getLoginUserInfo(){
        $header = Request::header();
        if (!empty($header['token'])) {
            $token = $header['token'];
        } else if (!empty(Request::param()['token'])) {
            $token = Request::param()['token'];
        }else {
            $token = '';
        }

        if (empty($token)) {
            return redirect(url('admin/login/index'));
            // return json(['code' => Error::NOT_LOGGED_CODE, 'message' => Error::PLEASE_LOGIN_FIRST]);
        }
        $redis = Cache::store('redis')->handler();
        $redis->select(3);

        $userInfo = $redis->get($token);
        $userInfo = json_decode($userInfo, true);
        return $userInfo;
    }


}